<?php

namespace app\admin\controller\sponsor;

use addons\epay\library\Service;
use app\admin\model\Myservice;
use app\common\controller\Backend;
use Exception;
use think\Db;
use Endroid\QrCode\QrCode;
use Yansongda\Pay\Pay;
use Yansongda\Pay\Gateways\Wechat;
use think\exception\PDOException;
use think\exception\ValidateException;
use app\admin\model\trades\assets\Card_log;
use app\common\controller\Wallet;
use think\Response;

/**
 * 举办人设置类
 *
 * @icon fa fa-circle-o
 */
class Sponsorbuy extends Backend
{

    protected $noNeedLogin = ['qrcode','buylist','notify'];
    protected $noNeedRight = '';

    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\trades\assets\Card;
        //print_r($this->model->getCardList());die;
        $this->view->assign('cardList',$this->model->getCardList());
    }

    public function import()
    {
        parent::import();
    }
    /**
     * 举办人购买首页
     */
    public function preindex()
    {
        $type = $this->request->request('type');
        
        if($type ==2){
            $result = Db::name("sponsor_order")->where('sponsorId = '.$this->auth->id.' and type in (5,6,7)')->order('type desc')->limit(1)->select();
        }else{
            $result = Db::name("sponsor_order")->where('sponsorId = '.$this->auth->id.' and type in (1,2,3,4)')->order('type desc')->limit(1)->select();
        }
        if($result){
            foreach ($result as $item =>$value){
                $result[$item]['tData'] = Db::name("sponsor_order_set")->where("type =".$value['type'])->find();
                $result[$item]['totalYear'] = $value['totalTime']/(365*24);
            }
        }
        $this->view->assign("type",empty($type)?'1':$type);
        $this->view->assign('pData', empty($result)?array():$result);
        return $this->view->fetch();
    }

    /**
     * 会议购买面板
     */
    public function index()
    {
        $result = Db::name("sponsor_order_set")->where('type in (5,6,7)')->order('type')->select();
        if($result){
            foreach ($result as $item =>$value){
                $result[$item]['detailArr'] = explode('$',$value['detailP']);
            }
        }

        $this->view->assign('pData', empty($result)?array():$result);
        return $this->view->fetch();
    }
    /**
     * 活动购买面板
     */
    public function personalindex()
    {
        $result = Db::name("sponsor_order_set")->where('type in (1,2,3,4)')->order('type')->select();
        if($result){
            foreach ($result as $item =>$value){
                $result[$item]['detailArr'] = explode('$',$value['detailP']);
            }
        }
        //dump($result);
        $this->view->assign('pData', empty($result)?array():$result);
        return $this->view->fetch('sponsor/sponsorbuy/personalIndex');
    }


    /**
     * 举办人购买
     */
    public function sponsorbuydetail()
    {
        $type = $this->request->request('type');
        //测试数据
        $result = Db::name("sponsor_order_set")->where('type',$type)->find();
        $this->view->assign('r', empty($result)?array():$result);
        $this->view->assign("type",$type);
        switch ($type) {
            case 1:
            case 2:
            case 3:
            case 4:
                $this->view->assign("deition",'商业版');
                return $this->view->fetch('sponsor/sponsorbuy/sponsorbuyPersonal');
                break;
            case 6:
                $vRoom = Db::name("v_activity_room_set")->where('type',$type)->select();
                $this->view->assign("deition",'商业版');
                $this->view->assign('vRoomsData', empty($vRoom)?array():$vRoom);
                return $this->view->fetch('sponsor/sponsorbuy/sponsorbuyBusiness');
                break;
            case 7:
                $vRoom = Db::name("v_activity_room_set")->where('type',$type)->select();
                $this->view->assign('vRoomsData', empty($vRoom)?array():$vRoom);
                $this->view->assign("deition",'企业版');
                return $this->view->fetch('sponsor/sponsorbuy/sponsorbuyEnterprise');
                break;

        }

    }

    /**
     * 举办人购买列表
     */
    public function buylist()
    {
        $result = Db::name("sponsor_order")->where('sponsorId',$this->auth->id)->select();

        if($result){
            foreach ($result as $item=>$value){
                $result[$item]['vRoomList'] = Db::name("sponsor_order_vroom")->where('orderId',$value['orderId'])->select();
            }
        }
        $this->view->assign('rows', $result);
        return $this->view->fetch();
    }


    /**
     * 生成订单
     */
    public function order()
    {

        $params = $this->request->param();
        //$planInfo = PlanFunc::planDetail($params['id'], $this->auth->id);
        $planInfo =Db::table('sponsor_order_set')->where('type='.$params['type'])->find();
        $orderData = array();
        $orderData['orderId'] = 'SP'.date("YmdHis") . mt_rand(100000, 999999);
        $orderData['status'] = '1';
        $orderData['type'] = $params['type'];
        $orderData['planName'] = $planInfo['name'];
        $orderData['sponsorId'] =$this->auth->id;
        $orderData['zhengNum'] = $params['xkzNumber'];
        $orderData['totalMoney'] = $params['totalFee'];
        $orderData['buyTime'] = time();
        $orderData['totalMonth'] = $params['jifeiPrice'];//月
        Db::table('sponsor_order')->insert($orderData);

        $config = self::getWechatConfig('wechat');
        $config['notify_url'] = "http://dev.onzoom.cn/admin/sponsor/sponsorbuy/notify/type/wechat";
        $wechat = Pay::wechat($config);
        $order = [
            'out_trade_no' => $orderData['orderId'],
            'body' => $orderData['planName'] ,
            //'total_fee' => $orderData['amount'] * 100,
            'total_fee' => 0.01*100,
        ];
        $result = $wechat->scan($order);
        $orderData['payurl'] = $result['code_url'];
//        $elseInfo['payurl'] = "http://w.kaihuibao.net/admin/expanding_services?ref=addtabs";
        $elseInfo['payurl'] = $result['code_url'];
        $elseInfo['payAmount'] = $orderData['totalMoney'];
        $elseInfo['orderNum'] = $orderData['orderId'];
        $elseInfo['distinct'] = "plan";
        $this->view->assign('elseInfo', $elseInfo);
        $this->view->assign('orderData', $orderData);
        $this->view->assign('type', 'pc');
        return $this->view->fetch("sponsor/sponsorbuy/serverorder");
    }
    /**
     * 购买返回地址
     * */
    public function returnurl()
    {
        if ($this->request->isAjax()) {
            //auth_id ,orderid共同判断
            $curentId  = $this->request->post("orderId");
            $sponsorId  = $this->auth->id;
            $mywhere =['orderId'=>$curentId,'sponsorId'=>$sponsorId];
            $curentOrder  = Db::name("sponsor_order")->where($mywhere)->find();
            $result = array('status'=>200,"total" =>1, "orderStatus" =>$curentOrder['status']);
            return json($result);
        }else{
            $result = array('status'=>0,"total" => 0, "rows" => 0);
            return json($result);
        }
    }

    /**
     * 购买通知
     * */
    public function notify()
    {
        $type = $this->request->param('type');
        $pay = Service::checkNotify($type);
        if (!$pay) {
            $data = '签名错误';
            return;
        }
        $data = $pay->verify();
        try {
            //$payamount = $type == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
            $out_trade_no = $data['out_trade_no'];
            $updataOrder =['status'=>2, 'transaction_id'=>$data['transaction_id']];
            if($data['result_code']==='SUCCESS'){
                Db::name("sponsor_order")->where("orderId", '=', $out_trade_no)->update($updataOrder);
            }
            //你可以在此编写订单逻辑
        } catch (\think\Exception $e) {
        }
        //你可以在这里你的业务处理逻辑,比如处理你的订单状态、给会员加余额等等功能
        //下面这句必须要执行,且在此之前不能有任何输出
        echo $pay->success();
        $this->success("恭喜你！支付成功!", addon_url("/sponsor/sponsorbuy/buylist"));
        return;

    }
    /**
     * 生成二维码
     * */
    public function qrcode()
    {
        $url = $this->request->param();
        $text = $this->request->get('text', $url['url']);
        $size = $this->request->get('size', 300);
        $padding = $this->request->get('padding', 15);
        $errorcorrection = $this->request->get('errorcorrection', 'medium');
        $foreground = $this->request->get('foreground', "#ffffff");
        $background = $this->request->get('background', "#000000");
        $logo = $this->request->get('logo');
        $logosize = $this->request->get('logosize');
        $label = $this->request->get('label');
        $labelfontsize = $this->request->get('labelfontsize');
        $labelhalign = $this->request->get('labelhalign');
        $labelvalign = $this->request->get('labelvalign');

        // 前景色
        list($r, $g, $b) = sscanf($foreground, "#%02x%02x%02x");
        $foregroundcolor = ['r' => $r, 'g' => $g, 'b' => $b];

        // 背景色
        list($r, $g, $b) = sscanf($background, "#%02x%02x%02x");
        $backgroundcolor = ['r' => $r, 'g' => $g, 'b' => $b];

        $qrCode = new QrCode();

          $qrCode->setSize($size);
          $qrCode->setText($text);
          $qrCode->setPadding($padding);
          $qrCode->setErrorCorrection($errorcorrection);
          $qrCode->setForegroundColor($foregroundcolor);
          $qrCode->setBackgroundColor($backgroundcolor);
          $qrCode->setLogoSize($logosize);
          $qrCode->setLabelFontPath(ROOT_PATH . 'public/assets/fonts/fzltxh.ttf');
          $qrCode->setLabel($label);
          $qrCode->setLabelFontSize($labelfontsize);
          $qrCode->setLabelHalign($labelhalign);
          $qrCode->setLabelValign($labelvalign);
          $qrCode->setImageType(QrCode::IMAGE_TYPE_PNG);
        //也可以直接使用render方法输出结果
        //$qrCode->render();
        return new Response($qrCode->get(), 200, ['Content-Type' => $qrCode->getContentType()]);
    }

    /**
     * 支付配置
     **/
    public static function getWechatConfig($type = 'wechat')
    {
        $config = get_addon_config('epay');
        $config = isset($config[$type]) ? $config[$type] : $config['wechat'];
        if ($config['log']) {
            $config['log'] = [
                'file' => LOG_PATH . '/epaylogs/' . $type . '-' . date("Y-m-d") . '.log',
                'level' => 'debug'
            ];
        }
        $config['notify_url'] = request()->root(true) . '/addons/epay/api/planNotify/type/' . $type;
        return $config;
    }



}
